package com.x.uikit.channel.feed;

import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.x.uikit.link.XParams;
import com.x.uikit.multistateview.IFeedLoadMoreView;
import com.x.uikit.multistateview.MultiStateListener;
import com.x.uikit.multistateview.MultiStater;

public abstract class AbstractFeedLoadMoreView extends FrameLayout implements IFeedLoadMoreView {
    protected OnLoadMoreListener mOnLoadMoreListener;
    protected final MultiStater mMultiStater = new MultiStater();
    protected XParams mLoadParams;

    public AbstractFeedLoadMoreView(@NonNull Context context) {
        super(context);
        mMultiStater.addListener(mMultiStateListener);
    }

    public void setLoadParams(XParams params) {
        this.mLoadParams = params;
    }

    public void setOnLoadMoreListener(OnLoadMoreListener listener) {
        mOnLoadMoreListener = listener;
    }

    public void reset() {
        mMultiStater.update(MultiStater.State.INIT, null);
    }

    public void finishLoad(boolean success, boolean hasData, XParams params) {
        if (success) {
            if (hasData) {
                mMultiStater.update(MultiStater.State.SUCCESS, params);
            } else {
                mMultiStater.update(MultiStater.State.EMPTY, params);
            }
        } else {
            mMultiStater.update(MultiStater.State.ERROR, params);
        }
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void onLoadMore() {
        if (mMultiStater.getState() != MultiStater.State.EMPTY) {
            mMultiStater.update(MultiStater.State.LOADING, mLoadParams);
            if (mOnLoadMoreListener != null) {
                mOnLoadMoreListener.onLoadMore(mLoadParams);
            }
        }

    }

    protected MultiStateListener mMultiStateListener = new MultiStateListener() {

        @Override
        public void onStateChanged(MultiStater.State newState, MultiStater.State oldState, XParams params) {
            updateViewByState(newState, oldState, params);
        }
    };

    protected abstract void updateViewByState(MultiStater.State newState, MultiStater.State oldState, XParams params);

    public interface OnLoadMoreListener {
        void onLoadMore(XParams params);
    }
}
